#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
/*
 * Zenlayer.com Inc.
 * Copyright (c) 2014-2020 All Rights Reserved.
 */
package ${package}.${artifactId}.data.mapper;

import ${package}.${artifactId}.data.model.BaseJsonDO;

import ${package}.${artifactId}.utils.JacksonUtil;
import ${package}.${artifactId}.utils.PcStringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * TODO 此方法 目的是所有 DO中json对象 不需要再配置 如果有效率问题 可以用XML，或者@MappedTypes @MappedJdbcTypes 代替
 *
 * @author yangshen
 * @version ${symbol_dollar} Id: CodeJsonTypeHandler.java, v 0.1  yangshen Exp ${symbol_dollar}
 * @date 2020-06-10 14:23:56
 */
public class JsonTypeHandler<T extends BaseJsonDO> extends BaseTypeHandler<T> {

    private static final Logger logger = LoggerFactory.getLogger(JsonTypeHandler.class);

    private static final String EXTEND_INFO_DO_PATH = "${package}.common.dal.dataobject.extend.";

    private Class<T> clazz;

    public JsonTypeHandler(Class<T> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        if (BaseJsonDO.class.isAssignableFrom(type)) {
            clazz = type;
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, this.toJson(parameter));
    }

    @Override
    public synchronized T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        try {

            Class<T> clazzcc = PcStringUtils.getclass(EXTEND_INFO_DO_PATH + PcStringUtils.camel(columnName));

            return this.toObject(rs.getString(columnName), clazzcc);
        } catch (ClassNotFoundException e) {
            logger.error("数据库列明跟对象明不一致,反解析失败");
            return null;
        }
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.toObject(rs.getString(columnIndex), clazz);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.toObject(cs.getString(columnIndex), clazz);
    }

    private String toJson(T object) {
        try {
            return JacksonUtil.bean2JsonToString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private T toObject(String content, Class<T> clazz) {
        if (content != null && !content.isEmpty()) {
            try {
                return JacksonUtil.json2Bean(content, clazz);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }

}
